<!--
 /**
 * Author: hongChengHao
 * Date: 2022-07-28 20:48
 * Desc: 生成海报
 */
-->
<template>
  <yy-page class="poster">
    <view v-if="!isComplete" :style="{ width: cansWidth + 'px', height: cansHeight + 'px' }">
      <canvas
        :style="{
          width: cansWidth + 'px',
          height: cansHeight + 'px',
          position: 'position',
          left: '-999px'
        }"
        canvas-id="poster"
        id="poster"
      ></canvas>
    </view>
    <view class="poster__poster" v-else>
      <image
        :style="{
          width: cansWidth + 'px',
          height: cansHeight + 'px',
          display: 'block'
        }"
        :src="tempFilePath"
      ></image>
    </view>
    <view v-if="isComplete" class="poster__button">
      <!-- #ifdef H5 -->
      <view @click="saveImg" class="btn">{{ isWxBrowswer ? '长按海报保存到相册' : '保存图片' }}</view>
      <!-- #endif -->
      <!--#ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO-->
      <view class="wx-btn">
        <u-button @click="saveImg">保存图片</u-button>
      </view>
      <!--#endif -->
    </view>
  </yy-page>
</template>
<script>
  import { dateFmt } from '@/utils/index'
  import { locPosterInfo } from '@/utils/locStore/data'
  // #ifdef H5
  import jrQrcode from 'jr-qrcode'
  // #endif
  export default {
    //  CouponPoster, NormalPoster,
    name: 'Poster',
    data() {
      return {
        ctx: null,
        cansWidth: 375,
        cansHeight: 810,
        avatarImgWidth: 51,
        avatarImgHeight: 51,
        projectImgWidth: 302,
        projectImgHeight: 326,
        qrImgWidth: 91,
        qrImgHeight: 91,
        bottomHeight: (397 / 1128) * 375,
        id: '',
        type: '',
        bgImg: 'https://public-oss-file.zmaxfilm.com/applet/img/my/bg-poster.png', // 背景图
        projectImg: '', // 中间图
        nickName: '', // 昵称
        date: dateFmt(new Date(), 'MM/DD HH:mm:ss'), // 分享日期
        avatar: '', // 头像
        qrUrl: '', // 小程序码
        name: '',
        describe: '',
        price: '',
        tempFilePath: '', // 生成路径
        isComplete: false, // 是否完成绘画
        rw: 1,
        rh: 1,
        // #ifdef H5
        isWxBrowswer: this.$tools.isWxBrowswer()
        // #endif
      }
    },
    async onLoad() {
      this.getScreenInfo()
      await this.getInfo()
      await this.getUserInfo()
    },
    onReady() {
      this.ctx = uni.createCanvasContext('poster', this)
      console.log(this.ctx, 'this')
      this.drawposter()
    },
    methods: {
      //生成H5二维码url
      createQrUrl(url) {
        const imgBase64 = jrQrcode.getQrBase64(url, {
          width: this.qrImgWidth * 2,
          height: this.qrImgWidth * 2,
          correctLevel: 3
        })
        return imgBase64
      },

      // 开始绘画
      async drawposter() {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        if (['coupon', 'normal'].includes(this.type)) {
          console.log('1')
          await this.drawWebImg({
            url: this.bgImg,
            x: 0,
            y: 0,
            width: this.cansWidth,
            height: this.cansHeight
          })
          console.log('2')
          await this.drawWebImg({
            url: this.avatar,
            x: 27 * this.widthScale,
            y: 36 * this.widthScale,
            width: this.avatarImgWidth * this.widthScale,
            height: this.avatarImgHeight * this.widthScale
          })
          await this.drawText({
            text: this.date,
            x: 87 * this.widthScale,
            y: 73 * this.widthScale,
            color: '#FFFFFF',
            size: 10,
            bold: false
          })
          await this.drawText({
            text: this.nickName,
            x: 87 * this.widthScale,
            y: 50 * this.widthScale,
            color: '#FFFFFF',
            size: 15,
            bold: true
          })
          console.log('3')
          await this.drawWebImg({
            url: this.projectImg,
            x: 37 * this.widthScale,
            y: 167 * this.widthScale,
            width: this.projectImgWidth * this.widthScale,
            height: this.projectImgHeight * this.widthScale,
            aspectFit: true
          })

          await this.drawText({
            text: this.name,
            x: 44 * this.widthScale,
            y: 520 * this.widthScale + 30,
            color: '#333333',
            size: 15,
            bold: true
          })
          this.changeRow({
            text: this.describe,
            x: 44 * this.widthScale,
            y: 550 * this.widthScale + 30,
            color: '#888888',
            size: 13,
            maxWidth: 302 * this.widthScale
          })
          await this.drawText({
            text: '￥',
            x: 44 * this.widthScale,
            y: 623 * this.widthScale + 25,
            color: '#FFB415',
            size: 19,
            bold: true
          })
          await this.drawText({
            text: this.price,
            x: 63 * this.widthScale,
            y: 623 * this.widthScale + 25,
            color: '#FFB415',
            size: 32,
            bold: true
          })
          console.log('4')
          console.log(this.qrImgWidth, this.qrImgHeight)
          await this.drawWebImg({
            url: this.qrUrl,
            x: 236 * this.widthScale,
            y: 610 * this.widthScale,
            width: this.qrImgWidth,
            height: this.qrImgHeight,
            noCache: true
          })
          console.log('5')
        } else {
          console.log('1')
          await this.drawWebImg({
            url: this.projectImg,
            x: 0,
            y: 0,
            width: this.cansWidth,
            height: 707 * this.widthScale,
            aspectFit: true
          })
          console.log('2')
          let loadImageHeight = 678 * this.widthScale
          console.log('loadImageHeight', loadImageHeight)
          if (this.loadImageHeight) {
            loadImageHeight = this.loadImageHeight - 30 * this.widthScale
          }
          console.log('loadImageHeight', loadImageHeight)
          await this.drawWebImg({
            url: 'https://public-oss-file.zmaxfilm.com/applet/img/my/bottomBg-poster.png',
            x: 0,
            y: loadImageHeight,
            width: this.cansWidth,
            height: this.bottomHeight
          })
          console.log('3')
          await this.drawWebImg({
            url: this.avatar,
            x: 22 * this.widthScale,
            y: loadImageHeight + 45,
            width: this.avatarImgWidth,
            height: this.avatarImgHeight
          })
          await this.drawText({
            text: this.nickName,
            x: 81 * this.widthScale,
            y: loadImageHeight + 52,
            color: '#000000',
            size: 15,
            bold: true
          })
          await this.drawText({
            text: this.date,
            x: 81 * this.widthScale,
            y: loadImageHeight + 72,
            color: '#000000',
            size: 10,
            bold: false
          })
          console.log('4')
          console.log(this.qrUrl, '------------')
          await this.drawWebImg({
            url: this.qrUrl,
            // #ifdef H5
            x: 261 * this.widthScale,
            y: loadImageHeight + 28,
            // #endif
            // #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
            x: 258 * this.widthScale,
            y: loadImageHeight + 25,
            // #endif
            width: this.qrImgWidth,
            height: this.qrImgHeight,
            noCache: true
          })
          console.log('ok-----')
        }

        this.tempFilePath = await this.saveCanvs()
        if (!this.tempFilePath) {
          this.tempFilePath = this.tempFilePathSave
        }

        this.isComplete = true
        uni.hideLoading()
      },
      // 画图
      drawWebImg(conf) {
        return new Promise((resolve, reject) => {
          // 图片短边显示
          const aspectFit = (imageWidth, imageHeight, canvasWidth, canvasHeight) => {
            const imageRate = imageWidth / imageHeight
            const canvasRate = canvasWidth / canvasHeight
            let [sx, sy, sw, sh] = []
            if (imageRate >= canvasRate) {
              sw = imageHeight * canvasRate
              sh = imageHeight
              sx = (imageWidth - sw) / 2
              sy = 0
            } else {
              sh = imageWidth / canvasRate
              sw = imageWidth
              sx = 0
              sy = (imageHeight - sh) / 2
            }
            return [sx, sy, sw, sh]
          }

          uni.downloadFile({
            url: `${conf.url}${conf.noCache ? '' : `?t=${Math.random().toString()}`}`,
            success: (res) => {
              if (conf.aspectFit) {
                uni.getImageInfo({
                  src: res.tempFilePath,
                  success: (image) => {
                    console.log(image.width)
                    console.log(image.height)
                    let imgArr = []

                    imgArr = aspectFit(image.width, image.height, conf.width, conf.height)

                    //背景图不做裁剪动作
                    this.loadImageHeight = (conf.width * image.height) / image.width
                    if (!['coupon', 'normal'].includes(this.type)) {
                      //根据背景图片 draw前定好尺寸 draw后改尺寸会压缩图片
                      this.cansHeight = this.loadImageHeight + this.bottomHeight - 30 * this.widthScale
                      this.ctx.drawImage(res.tempFilePath, conf.x, conf.y, conf.width ? conf.width : '', conf.height ? (conf.width * image.height) / image.width : '')
                      this.loadImageHeight = (conf.width * image.height) / image.width
                    } else {
                      this.ctx.drawImage(res.tempFilePath, imgArr[0], imgArr[1], imgArr[2], imgArr[3], conf.x, conf.y, conf.width ? conf.width : '', conf.height ? conf.height : '')
                    }

                    this.ctx.draw(true, () => {
                      resolve()
                    })
                  }
                })
              } else {
                this.ctx.drawImage(res.tempFilePath, conf.x, conf.y, conf.width ? conf.width : '', conf.height ? conf.height : '')
                this.ctx.draw(true, () => {
                  resolve()
                })
              }

              // console.log('this.ctx.drwaImage:', this.ctx.drwaImage)
            },
            fail: (err) => {
              uni.hideLoading()
              reject(err, '画图出错')
            }
          })
        })
      },
      // 画文本
      drawText(conf) {
        return new Promise((resolve) => {
          this.ctx.restore()
          this.ctx.setFillStyle(conf.color)
          if (conf.bold) this.ctx.font = `normal bold ${conf.size}px sans-serif`
          this.ctx.setFontSize(conf.size)
          let x = conf.x

          if (conf.center) {
            const len = this.ctx.measureText(conf.text)
            x = this.cansWidth / 2 - len.width / 2 + 2
          }

          this.ctx.fillText(conf.text, x, conf.y)
          this.ctx.draw(true, () => {
            this.ctx.save()
            resolve()
          })
        })
      },

      // 换行
      changeRow(conf) {
        const arrText = []
        let len2 = conf.text.length
        let strWidth = this.ctx.measureText(conf.text).width
        let str1 = conf.text
        while (strWidth > conf.maxWidth + 30 && len2-- > 0) {
          str1 = str1.slice(0, len2)
          strWidth = this.ctx.measureText(str1).width
        }
        const str2 = conf.text.slice(len2)
        arrText.push(str1)
        arrText.push(str2)

        arrText.forEach(async (item, index) => {
          await this.drawText({
            text: item,
            x: conf.x,
            y: conf.y + index * conf.size,
            color: conf.color,
            size: conf.size,
            bold: conf.bold
          })
        })
      },

      // canvas 转 图片
      saveCanvs() {
        return new Promise((resolve, reject) => {
          uni.canvasToTempFilePath(
            {
              x: 0,
              y: 0,
              canvasId: 'poster',
              success: (res) => {
                this.tempFilePathSave = res.tempFilePath
                resolve(res.tempFilePath)
              },
              fail: (err) => {
                uni.hideLoading()
                reject(err)
              }
            },
            this
          )
        })
      },

      // 保存到相册
      saveToPhoto() {
        uni.saveFile({
          tempFilePath: this.tempFilePath,
          success: (res) => {
            uni.saveImageToPhotosAlbum({
              //保存图片到系统相册。
              filePath: res.savedFilePath, //图片文件路径
              success: function () {
                uni.showToast({
                  title: '图片保存成功',
                  icon: 'none'
                })
              },
              fail: async (e) => {
                console.log(e)
                uni.showToast({
                  title: '图片保存失败',
                  icon: 'none'
                })
                this.isComplete = false
                this.ctx = uni.createCanvasContext('poster', this)
                this.drawposter()
              }
            })
          }
        })
      },

      // 保存图片
      saveImg() {
        this.$auth.getShareCount().then(() => {
          // #ifdef H5
          if (this.isWxBrowswer) {
            return
          } else {
            const Url = this.tempFilePath //图片路径，也可以传值进来
            const blob = new Blob([''], { type: 'application/octet-stream' }) //二进制大型对象blob
            const url = URL.createObjectURL(blob) //创建一个字符串路径空位
            const a = document.createElement('a') //创建一个 a 标签
            a.href = Url //把路径赋到a标签的href上
            a.download = Url.replace(/(.*\/)*([^.]+.*)/gi, '$2').split('?')[0]
            const e = new MouseEvent('click', (true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null))
            a.dispatchEvent(e)
            URL.revokeObjectURL(url)
          }
          // #endif
          // #ifndef H5
          uni.getSetting({
            success: (setRes) => {
              if (!setRes.authSetting['scope.writePhotosAlbum']) {
                // #ifdef MP-ALIPAY
                this.saveToPhoto()
                // #endif
                // #ifndef MP-ALIPAY
                uni.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success: () => {
                    this.saveToPhoto()
                  },
                  fail: () => {
                    //授权失败
                    uni.showModal({
                      title: '您已拒绝获取相册权限',
                      content: '是否进入权限管理，调整授权？',
                      success: (res) => {
                        if (res.confirm) {
                          //调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
                          uni.openSetting({
                            success: (res) => {
                              console.log(res.authSetting)
                            }
                          })
                        } else if (res.cancel) {
                          return uni.showToast({
                            title: '已取消！'
                          })
                        }
                      }
                    })
                  }
                })
                // #endif
              } else {
                this.saveToPhoto()
              }
            }
          })
          console.log('this.tempFilePath', this.tempFilePath)
          // #endif
        })
      },

      // // 获取图片信息
      // getImageInfo(imgUrl) {
      //   return new Promise((resolve) => {
      //     uni.downloadFile({
      //       url: imgUrl,
      //       success: (res) => {
      //         uni.getImageInfo({
      //           src: res.tempFilePath,
      //           success: (image) => {
      //             console.log(image.width)
      //             console.log(image.height)
      //             resolve()
      //           }
      //         })
      //       }
      //     })
      //   })
      // },

      getInfo() {
        return new Promise((resolve) => {
          // 解密
          const x = locPosterInfo.get()
          console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', x)
          this.projectImg = x.src
          // #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
          console.log(this.projectImg, x.qrUrl, 'x.qrUrlx.qrUrlx.qrUrl')
          this.qrUrl = x.qrUrl
          // #endif

          // #ifdef H5
          this.qrUrl = this.createQrUrl(x.qrUrl)
          // #endif

          this.name = x.name
          this.describe = x.describe || ''
          this.price = x.price
          // this.id = x.id
          this.type = x.type

          resolve()
        })
      },

      // 获取用户信息
      getUserInfo() {
        this.nickName = this.$store.state.userInfo.nickName || ''
        this.avatar = this.$store.state.userInfo.headImg || 'https://public-oss-file.zmaxfilm.com/pre/image/png/2022072710245889141.png'
      },

      // 获取手机屏幕可见区域宽高
      getScreenInfo() {
        const w = uni.getSystemInfoSync().windowWidth
        const h = uni.getSystemInfoSync().windowHeight
        this.rw = this.cansWidth / w
        this.rh = this.cansHeight / h

        this.cansWidth = w
        this.widthScale = w / 375
        if (!['coupon', 'normal'].includes(this.type)) {
          this.cansHeight = 707 * this.widthScale + this.bottomHeight - 29 * this.widthScale
        } else {
          this.cansHeight = 810 * this.widthScale
        }

        console.log(this.cansWidth, this.cansHeight, 'this.cansWidththis.cansWidth')

        console.log(w, h)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .poster {
    position: relative;
    display: flex;
    flex-direction: column;
    background: #fff;
    height: 100%;
    &__poster {
      display: block;
      flex: 1;
      height: calc(100vh - 120upx) !important;
      overflow-y: auto;
    }
    &__button {
      background: #fff;
      padding: 20upx;
      .btn {
        text-align: center;
        line-height: 80upx;
        width: 100%;
        height: 80upx;
        background: linear-gradient(135deg, #55baff 0%, #23e6d8 100%);
        border-radius: 10upx;
        color: #fff;
      }
    }
  }
</style>
